package czx.wt.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wangfan.endecrypt.utils.EndecryptUtils;
import com.wf.captcha.utils.CaptchaUtil;
import czx.wt.common.exception.BusinessException;
import czx.wt.common.response.ComResponseEnum;
import czx.wt.common.response.ResponseData;
import czx.wt.common.util.DataHandling;
import czx.wt.system.pojo.Authorities;
import czx.wt.system.pojo.Menu;
import czx.wt.system.pojo.User;
import czx.wt.system.service.IAuthoritiesService;
import czx.wt.system.service.IMenuService;
import czx.wt.system.service.IUserRoleService;
import czx.wt.system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.provider.Token;
import org.wf.jwtp.provider.TokenStore;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Author: ChenZhiXiang
 * @Date: 2019/6/20 20:57
 * @Description: 个人信息类
 */
@Api(value = "个人信息",tags = "个人信息")
@RestController
@RequestMapping("${api.version}")
public class MainController extends BaseController{

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IAuthoritiesService authoritiesService;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private IMenuService menuService;

    @ApiOperation(value = "获取个人信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping("/user/info")
    public Object getUserInfo(HttpServletRequest request) throws Exception {
        // 获取用户，  但用户的角色和权限为空
        User user = userService.selectById(getUserId(request));
        // 获取用户的权限
        List<Authorities> authoritiesList = new LinkedList<>();
        // 获取到Token
        Token token = getToken(request);
        // 从token中拿到权限
        String[] auths = token.getPermissions();
        for (String auth : auths){
            Authorities t = new Authorities();
            t.setAuthority(auth);
            authoritiesList.add(t);
        }
        return ResponseData.turnResponse(user);
    }

    @ApiOperation(value = "验证码接口")
    @ApiImplicitParams({})
    @GetMapping("/auth/code")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.outPng(3,request,response);
    }

    @ApiOperation(value = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "账号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "query")
    })
    @PostMapping("/user/login")
    public Object login(@RequestParam(value = "username") String username,@RequestParam(value = "password") String password,
                        @RequestParam(value = "code") String code,HttpServletRequest request) throws Exception {

        // 验证码不正确
        if (!CaptchaUtil.ver(code,request)){
            // 清除验证码
            CaptchaUtil.clear(request);
            throw new BusinessException(ComResponseEnum.USER1);
        }
        // 根据用户名查询用户
        User user = userService.findUserByUsername(username);

        if (null == user){
            return ResponseData.comResponse(ComResponseEnum.USER2);
        } else if (!user.getPassword().equals(EndecryptUtils.encrytMd5(password,username,3))){
            return ResponseData.comResponse(ComResponseEnum.USER3);
        }

        // 根据用户编码查询出角色编码
        String[] roleIds = DataHandling.arrToStr(userRoleService.getRoleByUserIds(user.getUserId()));
        //根据用户编码查询出权限
        String[] authorities = DataHandling.listToStr(authoritiesService.getAuthoritiesByUserId(user.getUserId()));
        // 创建Token,用户编码，权限，角色编码
        Token token = tokenStore.createNewToken(String.valueOf(user.getUserId()),authorities,roleIds);
        return ResponseData.turnResponse(token);
    }

    @ApiOperation(value = "获取所有菜单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping("user/menu")
    public Object findUserMenu(HttpServletRequest request) throws Exception {
        // 获取Token
        Token token = getToken(request);
        // 获取当前用户的权限
        String[] auths = token.getPermissions();
        // 查询所有的菜单
        EntityWrapper<Menu> wrapper = new EntityWrapper<>();
        wrapper.orderBy("sort_number",true);
        List<Menu> allMenu = menuService.selectList(wrapper);
        // 移除没有权限的菜单
        Iterator<Menu> iterator = allMenu.iterator();
        while (iterator.hasNext()){
            // 菜单实例
            Menu menu = iterator.next();
            boolean hasAuth = false;
            for (String str : auths){
                if (StringUtils.isBlank(menu.getAuthority()) || str.equals(menu.getAuthority())){
                    hasAuth = true;
                }
            }
            if (!hasAuth){
                iterator.remove();
            }
        }
        // 移除没用的菜单
        iterator = allMenu.iterator();
        while (iterator.hasNext()){
            Menu menu = iterator.next();
            if (StringUtils.isBlank(menu.getMenuUrl())){
                boolean hasParent = false;
                for (Menu menu1 : allMenu){
                    if (menu.getMenuId().equals(menu1.getParentId())){
                        hasParent = true;
                        break;
                    }
                }
                if (!hasParent){
                    iterator.remove();
                }
            }
        }
        return ResponseData.turnResponse(getMenuTree(allMenu,-1));
    }

    private List<Map<String, Object>> getMenuTree(List<Menu> menus, Integer parentId) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < menus.size(); i++) {
            Menu temp = menus.get(i);
            if (parentId.equals(temp.getParentId())) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", temp.getMenuName());
                map.put("icon", temp.getMenuIcon());
                map.put("url", StringUtils.isBlank(temp.getMenuUrl()) ? "javascript:;" : temp.getMenuUrl());
                map.put("subMenus", getMenuTree(menus, menus.get(i).getMenuId()));
                list.add(map);
            }
        }
        return list;
    }
}
